<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * List of user password, created password
 * 
 *
 * 
 * 
 * 
 */
class User_password_model extends MY_Model
{
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Get All User password used
     * 
     * @param type $user_id
     * @return type
     */
    public function get_user_passwords($user_id){
        return $this->get_many_by(array('user_id' => $user_id));
    }

    
    /**
     * 
     * @param str $password encrypted password
     * @return type
     */
    public function get_by_password($user_id, $password=null)
    {
        $where = array(
            'user_id' => $user_id,
            //'password' => $password,
            );
        $this->db->select('*');
        $this->db->where($where);
        
        $this->db->order_by('last_use','DESC');       
        $result = $this->db->get($this->_table)->result();
        return $result;

    }
    
    /**
     * 
     * @param int $user_id
     * @param str $password  encrypted password
     * @param int $limit password can only recycled.
     * @return boolean true=can still recycle; false=Need new password
     */
    public function passwordCheck($user_id, $password, $limit=5)
    {
        $user_password = $this->get_by_password($user_id, $password);
        if ($user_password){
            if ($user_password>=$limit){
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }
    /**
     * 
     * @param int $user_id
     * @param array $password none ecrypted
     *   plain
     *   encrypt
     * @param int $limit limit of password can recycle
     * 
     * Update:
     * v1.1  June 8 2015
     *     -> As per bob, you can only reuse you password after a five password creation.
     * 
     * @return boolean
     */
    public function save($user_id, $password=array(), $limit=5)
    {  
        $time = time();
        $update = array(
            'user_id'=>$user_id,
            'last_use'=>$time,
        );
        $new = true;
        $passwords = $this->get_by_password($user_id);
        if ($passwords && (count($passwords)>0)){
            $passIds = array();
            $i=0;
            foreach ($passwords as $key => $passwordObj) {
                
                // 
                // Comment out this logic as per update (v1.1  June 8 2015)
                //
                //if(($i ==0) &&$this->phpass->check( $password['plain'], $passwordObj->password )){
                //    $new = false;
                //    if ($passwordObj->num_use >= $limit){
                //        return false;
                //    }else{
                        //$this->primary_key = 'password';
                //        $update['num_use']=$passwordObj->num_use+1;
                        //$this->db->where(array('pass'))
                        //        ->set($update)
                        //        ->update($this->_table);
                //        $this->update($passwordObj->id, $update);
                //        return true;
                //    }
                //    break;// may match na xa eh.
                //}else{
                    // Collect all password that are not match to desired password
                    // So I can deleted them.
                    // UPDATE: Jun 8 2015 As per Bob I need to retain  those password.
                //    $passIds[] = $passwordObj->id;
                //}
                
                
                // Update for (v1.1  June 8 2015)
                if($this->phpass->check( $password['plain'], $passwordObj->password )){
                    $new = false;
                    if ($i>=($limit-1)){
                        // Update the Counter How many times he use it.
                        $update['num_use']=$passwordObj->num_use+1;
                        $this->update($passwordObj->id, $update);
                        return true;
                    }else{
                        return false;
                    }
                }
                $i++;
                
            }// foreach ($passwords as $key => $passwordObj) {
            
            //if ($passIds){
                // May 2015
                // As per Dyan You can alternate your password.
                // This is why I delete the other.
            //    $this->db->where_in('id', $passIds);
            //    $this->db->delete($this->_table);
            //}
            //return false;
        }
        if ($new){
            log_message("info", 'userId('.$user_id.') create new password('.$password.')');
            //$update['password']=$this->phpass->hash($password);
            $update['password']=$password['encrypt'];
            $update['timestamp']=$time;
            $update['num_use']=1;
            $this->insert($update);
        }

        return true; // replace the default return As per update (v1.1  June 8 2015)
    }
   
}